package com.atguigu.srb.sms.service.impl;

import com.atguigu.srb.base.exception.Assert;
import com.atguigu.srb.base.result.R;
import com.atguigu.srb.base.result.ResponseEnum;
import com.atguigu.srb.common.utils.RandomUtils;
import com.atguigu.srb.common.utils.RegexValidateUtils;
import com.atguigu.srb.sms.feign.ServiceCoreClient;
import com.atguigu.srb.sms.properties.SmsProperties;
import com.atguigu.srb.sms.service.SmsService;
import com.atguigu.srb.sms.utils.HttpUtils;
import org.apache.http.HttpResponse;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class SmsServiceImpl implements SmsService {
    @Resource
    ServiceCoreClient serviceCoreClient;
    @Resource
    StringRedisTemplate stringRedisTemplate;
//    @Resource
//    SmsProperties smsProperties;
    @Override
    public void sendMsg(String mobile) {
        //1、判断手机号码格式是否正确
        Assert.assertNotTrue(RegexValidateUtils.checkCellphone(mobile),
                ResponseEnum.MOBILE_ERROR);
        //获取验证码次数的key
        String countsKey = "sms:counts:"+mobile;
        //重复获取验证码的key
        String intervalKey = "sms:interval:"+mobile;
        //2、判断手机号码是否重复获取验证码
        //  一天限制3条   两分钟内不能重复获取
        String countStr = stringRedisTemplate.opsForValue().get(countsKey);
        Assert.assertTrue((!StringUtils.isEmpty(countStr) && Integer.parseInt(countStr)>=3),
                ResponseEnum.ALIYUN_SMS_LIMIT_CONTROL_ERROR);

        Assert.assertTrue(stringRedisTemplate.hasKey(intervalKey),
                ResponseEnum.ALIYUN_SMS_INTERVAL_CONTROL_ERROR);
        //注册完成后 再来添加 手机号重复注册验证
        R r = serviceCoreClient.checkMobile(mobile);
        Assert.assertTrue(r.getCode()!=0,ResponseEnum.ERROR);
        Assert.assertNotTrue(Boolean.parseBoolean(r.getData().get("flag").toString())
            , ResponseEnum.MOBILE_EXIST_ERROR);
        //远程访问service-core 判断手机号是否已被占用
        //3、生成验证码 发送
        String sixBitRandom = RandomUtils.getSixBitRandom();
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + SmsProperties.APPCODE);
        Map<String, String> querys = new HashMap<String, String>();
        querys.put("mobile", mobile); //手机号
        querys.put("param", "code:"+sixBitRandom); // 短信模板需要的参数
        querys.put("tpl_id", SmsProperties.TPLID);//短信模板：只能使用默认
        Map<String, String> bodys = new HashMap<String, String>();
        try {
//            HttpResponse response = HttpUtils.doPost(SmsProperties.HOST,
//                    SmsProperties.PATH, SmsProperties.METHOD, headers, querys, bodys);
//            String result = EntityUtils.toString(response.getEntity(), "UTF-8");
//
//            Map<String,String> map = JSON.parseObject(result, Map.class);
//            Assert.assertNotTrue(!(CollectionUtils.isEmpty(map) || !"00000".equals(map.get("return_code"))),
//                    ResponseEnum.ALIYUN_SMS_ERROR);
            //4、发送成功 保存验证码到redis中缓存
            stringRedisTemplate.opsForValue().set("sms:code:"+mobile,
                    sixBitRandom,10 , TimeUnit.MINUTES);
            //5、更新手机号获取验证码的次数
            //  一天限制3条   两分钟内不能重复获取
            //判断如果手机号是第一次获取验证码，初始化获取验证码的次数+设置过期时间

            if(!stringRedisTemplate.hasKey(countsKey)){
                stringRedisTemplate.opsForValue().set(countsKey,"1",1,TimeUnit.DAYS);
            }else{
                stringRedisTemplate.opsForValue().increment(countsKey);
            }
            //缓存一个过期时间为2分钟的数据
            stringRedisTemplate.opsForValue().set(intervalKey,
                    "1",2 , TimeUnit.MINUTES);
            //获取response的body
            //System.out.println(EntityUtils.toString(response.getEntity()));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void sendMessage(String mobile , String templateId,String money){
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + SmsProperties.APPCODE);
        Map<String, String> querys = new HashMap<String, String>();
        querys.put("mobile", mobile); //手机号
        querys.put("param", "code:"+money); // 短信模板需要的参数
        querys.put("tpl_id", SmsProperties.TPLID);//短信模板：只能使用默认
        Map<String, String> bodys = new HashMap<String, String>();
//            HttpResponse response = HttpUtils.doPost(SmsProperties.HOST,
//                    SmsProperties.PATH, SmsProperties.METHOD, headers, querys, bodys);
//            String result = EntityUtils.toString(response.getEntity(), "UTF-8");
//
//            Map<String,String> map = JSON.parseObject(result, Map.class);
//            Assert.assertNotTrue(!(CollectionUtils.isEmpty(map) || !"00000".equals(map.get("return_code"))),
//                    ResponseEnum.ALIYUN_SMS_ERROR);
            //4、发送成功 保存验证码到redis中缓存
        stringRedisTemplate.opsForValue().set("sms:money:"+mobile,
                money,10 , TimeUnit.MINUTES);
    }
}
